<?php
namespace Callback\Controller;

use Think\Log;

class AliyunLiveController extends BaseController
{
    private $logFile;

    public function _initialize()
    {
        $this->logFile = $logFile = LOG_PATH . 'Callback/' . date('Y-m-d') . '_aliyunlive.log';
    }

    /**
     * 推流回调，这里用于修改播放状态
     *
     * @return void
     */
    public function push()
    {
        $input = I('get.');
        Log::write(json_encode($input), Log::INFO, '', $this->logFile);
        if ($input['action'] == 'publish') { //开始推流
            D('Live/LiveRecord')->start($input['id']);
        } elseif ($input['action'] == 'publish_done') { //结束推流
            D('Live/LiveRecord')->pause($input['id']);
        }
    }

    /**
     * 录制回调
     * @return void
     */
    public function record()
    {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        Log::write($input, Log::INFO, '', $this->logFile);
        $record = D('Live/LiveRecord')->where(['stream_name' => $data['stream']])->find();
        if (end_with($data['uri'], '.mp4')) {
            $mp4UriArray = $record['mp4_record_uri'] ? explode(',', $record['mp4_record_uri']) : [];
            $mp4UriArray[] = $data['uri'];
            D('Live/LiveRecord')->where(['stream_name' => $data['stream']])->setField([
                'mp4_record_uri' => implode(',', $mp4UriArray),
            ]);
        } elseif (end_with($data['uri'], '.m3u8')) {
            $m3u8UriArray = $record['m3u8_record_uri'] ? explode(',', $record['m3u8_record_uri']) : [];
            $m3u8UriArray[] = $data['uri'];
            D('Live/LiveRecord')->where(['stream_name' => $data['stream']])->setField([
                'm3u8_record_uri' => implode(',', $m3u8UriArray),
            ]);
        }
        $record = D('Live/LiveRecord')->where(['stream_name' => $data['stream']])->find();
        if ($reocrd['mp4_record_uri'] && $record['m3u8_record_uri']) {
            D('Live/LiveRecord')->where(['stream_name' => $data['stream']])->setField([
                'status' => 3,
            ]);
        }
    }
}
